package com.frame.common.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.frame.app.core.rms.model.SystemUser;


public class MyUserDetailServiceImpl implements UserDetailsService {
	UserService userService;
	public UserService getUserService() {
		return userService;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	// 登入默认会调整到这里
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("MyUserDetailServiceImpl.loadUserByUsername");
		System.out.println("username is " + username);
//		try {
//			users = this.userService.findByUsersLogin(username);
//		} catch (LoginException e) {
//			throw new UsernameNotFoundException(username);
//		} catch (SystemRunException e) {
//			throw new UsernameNotFoundException(username);
//		}
//		if (users == null) {
//			throw new UsernameNotFoundException(username);
//		}else {
//			if(!users.getStatus()){
//				throw new UsernameNotFoundException("该用户处于锁定状态");
//			}
//		}
		String password = "";
		SystemUser systemUser = new SystemUser();
		systemUser.setCode(username);
		systemUser = systemUser.load();
		if(systemUser!=null){
			password = systemUser.getPassword();
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;
			//System.out.println(systemUser.getPassword());
			Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
			authSet.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS_INDEX"));
			Collection<GrantedAuthority> grantedAuths =authSet;
			boolean enables = true;
			User userdetail = new User(username,password,enables,accountNonExpired,credentialsNonExpired,accountNonLocked,grantedAuths);
			return userdetail;
		}
		return null;
	}
}